package com.snowRemovingUser.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jcraft.jsch.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.snowRemovingUser.domain.TCsvAbnormal;
import com.snowRemovingUser.mapper.TCsvAbnormalMapper;
import com.snowRemovingUser.service.ITCsvAbnormalService;
import com.snowRemovingUser.util.FileDownloadUtil;
import com.snowRemovingUser.util.SftpTransfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;

/**
 * 异常处理Service业务层处理
 *
 * @author lishiguang
 * @date 2023-05-08
 */
@Service
public class TCsvAbnormalServiceImpl implements ITCsvAbnormalService
{
    @Autowired
    private TCsvAbnormalMapper tCsvAbnormalMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Value("${linux.remoteFilePath}")
    private String remoteFilePath;

    @Value("${linux.localFilePath}")
    private String localFilePath;

    @Value("${linux.username}")
    private String username;

    @Value("${linux.password}")
    private String password;

    @Value("${linux.ip}")
    private String ip;

    @Value("${linux.port}")
    private String port;

    @Value("${formalAttire.serverEnabled}")
    private Boolean serverEnabled;

    @Value("${formalAttire.username}")
    private String username2;

    @Value("${formalAttire.password}")
    private String password2;

    @Value("${formalAttire.ip}")
    private String ip2;

    @Value("${formalAttire.destinationFilePath}")
    private String destinationFilePath;






    @Autowired
    private SftpTransfer sftpTransfer;



    /**
     * 查询异常处理
     *
     * @param id 异常处理主键
     * @return 异常处理
     */
    @Override
    public TCsvAbnormal selectTCsvAbnormalById(Long id)
    {
        return tCsvAbnormalMapper.selectTCsvAbnormalById(id);
    }

    /**
     * 查询异常处理列表
     *
     * @param tCsvAbnormal 异常处理
     * @return 异常处理
     */
    @Override
    public List<TCsvAbnormal> selectTCsvAbnormalList(TCsvAbnormal tCsvAbnormal) {


        List<SysUser> sysUsers = sysUserMapper.selectUserList(new SysUser());
        Map<Long, SysUser> SysUserByUserId = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));

        //查询需要分页
        PageDomain pageDomain = TableSupport.getPageDomain();
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), pageDomain.getOrderBy());
        List<TCsvAbnormal> tCsvAbnormals = tCsvAbnormalMapper.selectTCsvAbnormalList(tCsvAbnormal);

        for (TCsvAbnormal csvAbnormal : tCsvAbnormals) {

            if (csvAbnormal.getProcesUser()!=null){

                csvAbnormal.setProcesUserName(SysUserByUserId.get(csvAbnormal.getProcesUser()).getNickName());
            }else {

                csvAbnormal.setProcesUserName("暂无人员处理");
            }

        }
        //分页
        Page<TCsvAbnormal>  tCsvAbnormalsPage =(Page<TCsvAbnormal> )tCsvAbnormals;
        return tCsvAbnormalsPage;
    }

    /**
     * 新增异常处理
     *
     * @param tCsvAbnormal 异常处理
     * @return 结果
     */
    @Override
    public int insertTCsvAbnormal(TCsvAbnormal tCsvAbnormal)
    {
        return tCsvAbnormalMapper.insertTCsvAbnormal(tCsvAbnormal);
    }

    /**
     * 修改异常处理
     *
     * @param tCsvAbnormal 异常处理
     * @return 结果
     */
    @Override
    public int updateTCsvAbnormal(TCsvAbnormal tCsvAbnormal)
    {
        return tCsvAbnormalMapper.updateTCsvAbnormal(tCsvAbnormal);
    }

    /**
     * 批量删除异常处理
     *
     * @param ids 需要删除的异常处理主键
     * @return 结果
     */
    @Override
    public int deleteTCsvAbnormalByIds(Long[] ids)
    {
        return tCsvAbnormalMapper.deleteTCsvAbnormalByIds(ids);
    }

    /**
     * 删除异常处理信息
     *
     * @param id 异常处理主键
     * @return 结果
     */
    @Override
    public int deleteTCsvAbnormalById(Long id)
    {
        return tCsvAbnormalMapper.deleteTCsvAbnormalById(id);
    }


    /**
     *  确认自行处理异常
     * @param id
     * @return
     */
    @Override
    public int handleDiscretion(Long id) {

        TCsvAbnormal tCsvAbnormal = tCsvAbnormalMapper.selectTCsvAbnormalById(id);

        if (tCsvAbnormal.getStatus()==1){

            throw new RuntimeException("该异常已经处理无需重复处理");

        }
        //文件下载成功之后添加处理人、修改状态和处理时间
        tCsvAbnormal.setStatus(1);
        tCsvAbnormal.setProcesUser(SecurityUtils.getUserId());
        tCsvAbnormal.setProcessTime(new Date());
        return tCsvAbnormalMapper.updateTCsvAbnormal(tCsvAbnormal);
    }

    /**
     *  一键处理异常信息
     * @param id
     * @return
     */
    @Override
    public int handleAbnormal(Long id) {


        TCsvAbnormal tCsvAbnormal = tCsvAbnormalMapper.selectTCsvAbnormalById(id);

        if (tCsvAbnormal.getStatus()==1){

            throw new RuntimeException("该异常已经处理无需重复处理");

        }

        String abnormalContent = tCsvAbnormal.getAbnormalContent();
        String fileName = abnormalContent.substring(0, 26);
        //String fileName = "hsoIndex2023050901z.tar.gz";
        //文件下载路径+文件名
        String remoteFilePathName = remoteFilePath+fileName;

        boolean downloadFile;

        // serverEnabled为true的话 就走正式服方式上传文件
        if (serverEnabled){

             downloadFile =sftpTransfer.fileTransfer(fileName);

        } else {

            //连接到linux远程处理文件
             downloadFile = FileDownloadUtil.downloadFile(remoteFilePathName, localFilePath, username, password, ip, Integer.parseInt(port));

        }

        if (downloadFile==false){

            throw new RuntimeException("一键处理异常失败");
        }

        //文件下载成功之后添加处理人、修改状态和处理时间
        tCsvAbnormal.setStatus(1);
        tCsvAbnormal.setProcesUser(SecurityUtils.getUserId());
        tCsvAbnormal.setProcessTime(new Date());
        return tCsvAbnormalMapper.updateTCsvAbnormal(tCsvAbnormal);
    }


    /**
     *  HsoIndex 文件上传
     * @param file
     * @param id
     * @return
     */
    @Override
    public int uploadByHsoIndex(MultipartFile file, Long id) throws IOException, JSchException, SftpException {

        TCsvAbnormal tCsvAbnormal = tCsvAbnormalMapper.selectTCsvAbnormalById(id);

        if (tCsvAbnormal.getStatus()==1){

            throw new RuntimeException("该异常已经处理无需重复处理");

        }

        if (!(file.getOriginalFilename().equals(tCsvAbnormal.getAbnormalContent().substring(0, 26)))){

            throw new RuntimeException("上传的文件和缺少的异常文件不一致,请上传对应的文件");

        }

        // serverEnabled为true的话 就走正式服方式上传文件
        if (serverEnabled){

            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 创建SFTP连接
            JSch jSch = new JSch();
            Session session = jSch.getSession(username2, ip2,22);
            session.setPassword(password2);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();
            // 将文件上传至服务器
            sftpChannel.put(file.getInputStream(), destinationFilePath+fileName);
            // 关闭SFTP连接
            sftpChannel.exit();
            session.disconnect();

        } else {

            // 处理上传的文件
            InputStream inputStream = new GZIPInputStream(file.getInputStream());
            String filePath =  localFilePath + file.getOriginalFilename();// 文件要保存到本地的路径
            FileOutputStream outputStream = new FileOutputStream(new File(filePath));
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();

        }

        //文件下载成功之后添加处理人、修改状态和处理时间
        tCsvAbnormal.setStatus(1);
        tCsvAbnormal.setProcesUser(SecurityUtils.getUserId());
        tCsvAbnormal.setProcessTime(new Date());
        return tCsvAbnormalMapper.updateTCsvAbnormal(tCsvAbnormal);
    }

}
